<?php

/**
 * irequest
 * Filter class for iwebform
 * @author Talha Buğra Bulut talhabulut@hotmail.com
 */
class ifilter {

    public function __construct() {
        
    }

    public function filter($val, $filters) {
        $out = $val;

        if (isset($filters['strip_tags'])) {
            $out = $this->strip_tags($out);
        }

        if (isset($filters['strip_new_lines'])) {
            $out = $this->strip_new_lines($out);
        }

        if (isset($filters['trim'])) {
            $out = $this->trim($out);
        }

        if (isset($filters['substr'])) {
            $out = $this->substr($out, $filters['substr']['start'], $filters['substr']['length']);
        }

        if (isset($filters['int'])) {
            $out = $this->int($out);
        }

        if (isset($filters['in_array'])) {
            if (!$this->in_array($val, $filters['in_array']['haystack'])) {
                $out = null;
            }
        }

        if (isset($filters['null'])) {
            $out = $this->null($out);
        }

        return $out;
    }

    public function strip_tags($val, $allowable_tags=null) {
        return strip_tags($val, $allowable_tags);
    }

    public function strip_new_lines($val) {
        return str_replace(array("\n", "\r"), " ", $val);
    }

    public function trim($val) {
        return trim($val);
    }

    public function substr($val, $start, $length) {
        $str = strip_tags($val);
        $str = trim($str);
        preg_match_all("/./u", $str, $ar);
        if (strlen($str) > $length) {
            return join("", array_slice($ar[0], $start, $length));
        } else {
            return join("", array_slice($ar[0], $start, $length));
        }
    }

    public function int($val) {
        if (is_numeric($val)) {
            return intval($val);
        } else {
            return null;
        }
    }

    public function in_array($val, $haystack) {
        if (in_array($val, $haystack)) {
            return true;
        } else {
            return false;
        }
    }

    public function null($val) {
        if (strlen(trim($val)) == 0) {
            return null;
        } else {
            return $val;
        }
    }

}

?>